﻿//global variables
var isBrowserIE = false;
var isMaskpicMoving = false;
var autoScroll = null;
//for show tools
$(document).ready(function() {
	isBrowserIE = document.all && window.external;
	// Hide all the tooltips
	actionTools();
	//accelerate to top
	$('#elevator').click(function() {
		accelerateToTop(0.4, 10);
		return false;
	});
	//for mask layer
	closeMaskEvent();
	//for moving and showing mask picture
	maskPictureEffect();
	//for new message
	initMsgSettings()
	//slider
	slider();
});
//pic action tools for user
function actionTools(){
	$(".box").hover(function() { // Mouse over
		$(".likebtn",this).fadeIn("fast");
		$(".collectbtn",this).fadeIn("fast");
	},
	function() { // Mouse out
		$(".likebtn",this).fadeOut("fast");
		$(".collectbtn",this).fadeOut("fast");
	});
}
//for flash slider
function slider(){
	var lazyScroll = null;
	$(".navi li").each(function(i) {
		$(this).unbind();
		$(this).hover(function() {
			//change active class first
			if( $(".navi li.active") != this){
				$(".navi li.active").removeClass("active");
				$(this).addClass("active");
				if(lazyScroll!=null){
					clearTimeout(lazyScroll);
				}
				lazyScroll = setTimeout(function(){ 
					var lft = -1*i*960+"px";
					$(".items").animate({"left":lft}, "slow");
					},200);
			}
			if(autoScroll != null){
				clearTimeout(autoScroll);
				autoScroll = null;
			}
		},
		function() {
			if(lazyScroll!=null){
				clearTimeout(lazyScroll);
			}
			sliderAutoScroll(false);
		})
	});
	sliderAutoScroll(true);
}

function sliderAutoScroll(isScroll){
	if(isScroll){
		var currentLft = parseInt($(".items").css("left"));
		var lft = (currentLft-960 < -5760) ? 0 : (currentLft-960);
		$(".navi li.active").removeClass("active");
		$(".navi li").each(function(i) {
			if(i == Math.abs(lft)/960){
				$(this).addClass("active");
				return false;
			}
		});
		$(".items").animate({"left":lft+"px"}, "slow");
	}
	autoScroll = setTimeout("sliderAutoScroll(true)", 5000);
}

function closeMaskEvent(){
	$(document).keydown(function(event) {
		if (event.which == 27 && $('#mask-board').css("display") != 'none') {
			coverMask();
		}
	});
	//for close mask
	$("#mask-close").click(function(){
		coverMask(); 
	});
	
	$("#mask-layer").click(function(){
		coverMask(); 
	});
}

function maskPictureEffect(){
	//for moving mask-board picture
	$("#mask-pic-board").mouseenter(function() {
		var img_height = $("#pic-board img").height();
		var board_height = $("#pic-board").height();
		var board_scroll = document.getElementById("pic-board").scrollTop;
		if( img_height > board_height ){
			if( board_scroll < img_height - board_height ){
				$("#pic-up").css("display", "block");
			}
			if( document.getElementById("pic-board").scrollTop>0 ){
				$("#pic-down").css("display", "block");
			}
		}
	});
	
	$("#mask-pic-board").mouseleave(function() {
		if( $("#pic-board img").height()>$("#pic-board").height() ){
			$("#pic-up").css("display", "none");
			$("#pic-down").css("display", "none");
		}
	});
}

function afterLoadMaskPicture(){
	$("#pic-up").mouseover(function() {
		if( $("#pic-board img").height()>$("#pic-board").height() ){
			$("#pic-down").css("display", "block");
			isMaskpicMoving = true;
			acceleratePicUp(0.1, 10);
		}
	});
	$("#pic-up").mouseout(function() {
		isMaskpicMoving = false;
	});	
	$("#pic-down").mouseover(function() {
		if( document.getElementById("pic-board").scrollTop>0 ){
			$("#pic-up").css("display", "block");
			isMaskpicMoving = true;
			acceleratePicDown(0.1, 10);
		}
	});
	
	$("#pic-down").mouseout(function() {
		isMaskpicMoving = false;
	});
}
function maskComment(obj, itemId){
	var url = "doAysnComment.htm";
	var userId=$('#blackholeid').val();
	var userInfoUrl = "phome.htm?userid=" + userId;
	var imgSrc = $('#img_head').attr('src') == undefined ? "images/small-weibo.jpg" : $('#img_head').attr('src');
	var redUrl = "login.html?redircetUrl=" + $('#redirect').html();
	var content = $(".picinputtxt").val();
	var userNick = $('#blackholename').val();
	$.post(
	url, 
	{
		itemid: itemId,
		comment: content,
		redirectUrl: redUrl
	},
	function(ret) {
		if (ret.success == 'false') {
			if (ret.redirect == 'true') {
				window.location.href = redUrl;
			} else {
				if (ret.valid = 'false') {
					//to do
				}
			}
		} else {
			var html = "<li><div class='mask-comment-con'><a href='./phome.htm?userid=1' target='_blank' class='mask-comment-head'><img src='./images/header/head_" +userId+ ".jpg'></a><a href='./phome.htm?userid=1' target='_blank' class='comment-nick'>" + userNick + "：</a>" +content+ "</div></li>";
			$(".mask-comment-list ul").append(html);
			$(".picinputtxt").attr("value","");
		}
	},
	"json");
}
function initMsgSettings(){
	$("#closeTip").click(function(){$("#message-tip-box").fadeOut("fast");});
}
//push message function 
function pushMessage(atype, msgcount){
	switch (msgcount) {
		//new fans
	case 1:
		{
			$("#message-tip-box ul").append("<li>"+msgcount+"位新圈友，<a href='index.htm' target='_blank' onClick='rmMsgLink(this)'>查看新圈友</a></li>");
			$("#message-tip-box").fadeIn();
			break;
		}
		//new comment
	case 2:
		{
			$("#message-tip-box ul").append("<li>"+msgcount+"条新评论，<a href='index.htm' target='_blank' onClick='rmMsgLink(this)'>查看新评论</a></li>");
			$("#message-tip-box").fadeIn();
			break;
		}
		//new fans
	case 4:
		{
			$("#message-tip-box ul").append("<li>"+msgcount+"个新收藏，<a href='index.htm' target='_blank' onClick='rmMsgLink(this)'>查看新收藏</a></li>");
			$("#message-tip-box").fadeIn();
			break;
		}
		//new message
	case 8:
		{
			$("#message-tip-box ul").append("<li>"+msgcount+"条新消息，<a href='index.htm' target='_blank' onClick='rmMsgLink(this)'>查看新消息</a></li>");
			$("#message-tip-box").fadeIn();
			break;
		}
	default:
		{
			break;
		}
	}
	
}
function rmMsgLink(obj){
	$(obj).parent().remove();
}

//for mask login
function popLogin(){
	var html = "<div id='mask-login'></div>";
	$("body").append(html);
	$("#mask-login").height($(document).innerHeight());
	$("#mask-login").width($document.innerWidth());
}
function coverMask() {
	//hide mask-board first
	$('#mask-board').animate({
		"opacity": "0",
		"width": "0",
		"height": "0"
	},
	"slow",
	function() {
		$('#mask-board').css("display", "none");
	});
	//hide mask-close at last
	$('#mask-layer').fadeOut("slow");
	
	//open scroll
	document.getElementsByTagName('body')[0].style.overflow = 'scroll';
	document.getElementsByTagName('body')[0].scroll = "yes";
}

function showMask(obj) {
	//adjust document scroll
	document.getElementsByTagName('body')[0].style.overflow = 'hidden';
	document.getElementsByTagName('body')[0].scroll = "no";
	
	//show mask-layer first
	$('#mask-layer').fadeIn("slow");
	
	//calc mask-board and mask-close postion
	var mask_top = (window.innerHeight-620)/2;
	var mask_left = (window.innerWidth-810)/2;
	if(mask_left < 0){
		mask_left = 0;
	}
	if(mask_top < 0){
		mask_top = 0;
	}
	$('#mask-board').css({"top": mask_top,"left":mask_left});
	$('#mask-board').css("display", "block");
	
	//show mask-board at last
	$('#mask-board').animate({
		"opacity": "1",
		"width": "810px",
		"height": "620px",
	},
	700);
	$('#mask-board .mask-board-wrapper').html("<div class='loading'><img src='images/loading.gif' title='请耐心等待' alt='loading……'></div>");
	$.post("./asynGetMaskItem.htm", 
		{itemId:$(obj).parent().parent().attr("item-id")},
		function(data){
			$('#mask-board .mask-board-wrapper').html(data);
			eval("afterLoadMaskPicture()");
		});
}

//picture up and down
function acceleratePicUp(acceleration, time) {
	//moving condition
	if(isMaskpicMoving){
		time = time || 10;
		var delta = 4*(0.4+acceleration);
		var pic_board = document.getElementById("pic-board");
		var picHeight = $("#pic-board img").height();
		var calcHeight = $("#pic-board").height() + pic_board.scrollTop + delta;
		pic_board.scrollTop += delta;
		if (calcHeight < picHeight) {
			//accelerate moving
			acceleration += 0.4;
			var invokeFunction = "acceleratePicUp(" + acceleration + ", " + time + ")";
			window.setTimeout(invokeFunction, time);
		} else {
			$("#pic-up").css("display", "none");
		}
	}
}
function acceleratePicDown(acceleration, time) {
	//moving condition
	if(isMaskpicMoving){
		time = time || 10;
		var delta = 4*(0.4+acceleration);
		var pic_board = document.getElementById("pic-board");
		var calcHeight =  pic_board.scrollTop - delta;
		pic_board.scrollTop -= delta;
		if (calcHeight > 0) {
			//accelerate moving
			acceleration += 0.4;
			var invokeFunction = "acceleratePicDown(" + acceleration + ", " + time + ")";
			window.setTimeout(invokeFunction, time);
		} else {
			$("#pic-down").css("display", "none");
		}
	}
}

function picUp() {
	var pic_h = $("#pic-board img").height();
	if(pic_h>500){
		document.getElementById("pic-board").scrollTop += 18;
	}
}
function picDown() {
	var pic_h = $("#pic-board img").height();
	if(pic_h>500){
		document.getElementById("pic-board").scrollTop -= 18;
	}
}
//for goto top
$(document).scroll(function() {
	if ($(document).scrollTop() >= 100) {
		$('#gotop').fadeIn('slow');
	} else {
		$('#gotop').fadeOut('slow');
	}
});

//accelerate to top
function accelerateToTop(acceleration, time) {
	acceleration = acceleration || 0.1;
	time = time || 15;
	var x1 = 0;
	var y1 = 0;
	var x2 = 0;
	var y2 = 0;
	var x3 = 0;
	var y3 = 0;
	if (document.documentElement) {
		x1 = document.documentElement.scrollLeft || 0;
		y1 = document.documentElement.scrollTop || 0;
	}
	if (document.body) {
		x2 = document.body.scrollLeft || 0;
		y2 = document.body.scrollTop || 0;
	}
	var x3 = window.scrollX || 0;
	var y3 = window.scrollY || 0;

	var x = Math.max(x1, Math.max(x2, x3));
	var y = Math.max(y1, Math.max(y2, y3));
	var speed = 1 + acceleration;
	window.scrollTo(Math.floor(x / speed), Math.floor(y / speed));
	if (x > 0 || y > 0) {
		var invokeFunction = "accelerateToTop(" + acceleration + ", " + time + ")";
		window.setTimeout(invokeFunction, time);
	}
}
//append block of comment
function commentAppend(appendLink) {
	var curCol = parseInt(appendLink.parentNode.getAttribute("col-id"));
	var curRow = parseInt(appendLink.parentNode.getAttribute("row-id"));
	var itemId = appendLink.parentNode.getAttribute("item-id");
	var imgSrc = $('#img_head').attr('src') == undefined ? "images/small-weibo.jpg" : $('#img_head').attr('src');

	$(".box").each(function() {
		var colNum = parseInt($(this).attr("col-id"));
		var rowNum = parseInt($(this).attr("row-id"));
		if (colNum == curCol && rowNum == curRow) {
			if( $(this).children('.commenntappend').length>0){
				return false;
			} else {
				var more_cmt = $(this).children('.more');
				var html = "<div class='comment commenntappend'><a class='commenthead' href='phome.htm?userid=" + $('#blackholeid').val() + "'><img src='" + imgSrc + "' /></a><textarea class='comment-text' placeholder='添加评论' onClick='showHeadImg(this)' ></textarea><a class='commentbtn' href='#' onClick='doAsycComment(" + itemId + ",this);return false;'></a></div>";
				if( more_cmt.length > 0){
					//append comment box
					$(html).insertBefore(more_cmt);
				} else {
					$(this).append(html);
				}
			}
		}
		if (colNum == curCol && rowNum > curRow) {
			$(this).css('top', '+=56px');
		}
	});
}

function showHeadImg(imgObj) {
	var commentObj = $(imgObj).parent('.comment');
	$('a img', commentObj).addClass('comment-head-show');
}

// async to comment
function doAsycComment(id, clickObj) {
	var content = clickObj.parentNode.childNodes[1].value;
	if(content.length>0){

		var userNick = $('#blackholename').val();
		var redUrl = "login.html?redircetUrl=" + $('#redirect').val();
		if( userNick.length > 2){
			var url = "doAysnComment.htm";
			var userInfoUrl = "phome.htm?userid=" + $('#blackholeid').html();
			var imgSrc = $('#img_head').attr('src') == undefined ? "images/small-weibo.jpg" : $('#img_head').attr('src');
			$.post(
			url, {
				itemid: id,
				comment: content,
				redirectUrl: redUrl
			},
			function(data) {
				$(clickObj).parent().html("<a class='headimg' href='" + userInfoUrl + "'><img src='" + imgSrc + "' /></a><p><a href='" + userInfoUrl + "' class='author'>" + userNick + ":</a>" + content + "</p>");
				//parse JSON content
				var ret = $.parseJSON(data);
				if (ret.success == 'false') {
					if (ret.redirect == 'true') {
						window.location.href = redUrl;
					} else {
						if (ret.valid = 'false') {
							//to do
						}
					}
				} else {
					//get
					$(clickObj).parent().html("<a class='headimg' href='" + userInfoUrl + "'><img src='" + imgSrc + "' /></a><p><a href='" + userInfoUrl + "' class='author'>" + userNick + "</a>" + content + "</p>");

				}
			},
			"JSON");
		} else {
			window.location.href = redUrl;
		}
	}
}

function adjustCommentPostion(objSelector) {
	var picHeight = $(objSelector).attr('height') + 56;
	var clientHeight = $(window).height();
	if (picHeight > clientHeight) {
		var offest = picHeight / 2;
		$(document).animate({
			'scrollTop': '+=' + offest
		},
		'slow');
	}
}

function collect(collectObj) {
	var itemId = collectObj.parentNode.getAttribute("item-id");
	var url = "asynSetUserLike.htm";
	var userId = document.getElementById("blackholeid").value;
	if( userId != '0'){
		$.post( "./asynSetUserLike.htm", 
		{ itemid : itemId },
		function(ret) {
			//parse json
			if (ret.success == 'false') {
				if (ret.redirect == 'true') {
					window.location.href = loginUrl + '?redircetUrl=' + redUrl;
				} else {
					//change collection menu;
					bugReport(location.href,"itemId="+itemId+" collect failed!");
				}
			} else {
				//change collection menu;
				if($(collectObj).hasClass('cancelbtn')){
					$(collectObj).removeClass('cancelbtn');
					$(collectObj).html("<span><em></em>收藏</span>");
				} else {
					$(collectObj).addClass('cancelbtn');
					$(collectObj).html("<span><em></em>取消收藏</span>");
				}
			}
		},
		"text");
	} else {
		popLogin();
	}
}

function bugReport(url, msg){
	var bugUrl = "getBugReport.htm";
	$.post(
		bugUrl, 
		{
			bugurl: url,
			message: msg
		});
}


function iwantyou(pointObj) {
	var itemId = pointObj.getAttribute("like-id");
	$.post( "./asynSetUserLike.htm", 
		{ itemid : itemId },
		function(ret) {
			//parse json
			if (ret.success == 'false') {
				
			} else {
				var likeCount = document.getElementById(itemId+"-count").value;
				alert(likeCount);
			}
		},
		"text");
}